<template>
  <a-upload :accept="accept" :show-upload-list="false" :custom-request="onImport" :multiple="multiple">
    <a-button type="primary" :loading="onImportLoading"> 导入 </a-button>
  </a-upload>
</template>

<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import axios from 'axios'

const emit = defineEmits(['success'])
const onImportLoading = ref(false)
const props = defineProps({
  accept: {
    type: String,
    default: '.doc,.docx,.xlsx,.rtf,.xml,.txt,.pdf'
  },
  url: {
    type: String,
    default: ''
  },
  multiple: {
    type: Boolean,
    default: false
  }
})

const onImport = async (options) => {
  onImportLoading.value = true
  const { file } = options

  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    message.error('上传文件最大10MB!')
    onImportLoading.value = false
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  try {
    const { data: res } = await axios.post('/api/v1' + props.url, formData, { headers: { 'Content-Type': 'multipart/form-data' } })
    onImportLoading.value = false
    if (res.code !== 0) return message.error(res.msg)
    message.success(res.msg || '导入成功')
    emit('success')
  } catch (error) {
    onImportLoading.value = false
    message.error('导入失败')
  }
}
</script>
<style lang="less" scoped></style>
